home *** CD-ROM | disk | FTP | other *** search
/ Programming Microsoft Visual Basic .NET / Programming Microsoft Visual Basic .NET (Microsoft Press)(X08-78517)(2002).bin / 02 modules and namespaces / modulesdemo / mathfunctions.vb < prev    next >
Encoding:
Text File  |  2001-07-28  |  1.9 KB  |  60 lines

  1. ' this module demonstrate that the Sub New procedure can be used to 
  2. ' initialize module variables
  3.  
  4. Module MathFunctions
  5.     ' A public constant
  6.     Public Const DOUBLEPI As Double = 6.28318530717958
  7.  
  8.     ' A private array
  9.     Private factValues(169) As Double
  10.  
  11.     Sub New()
  12.         ' Evaluate all possible values in advance.
  13.         Dim i As Integer
  14.         factValues(0) = 1
  15.         For i = 1 To 169
  16.             factValues(i) = factValues(i - 1) * CDbl(i)
  17.         Next
  18.     End Sub
  19.  
  20.     ' Return the Factorial of a number in the range 0-169.
  21.     Function Factorial(ByVal n As Integer) As Double
  22.         ' Check the argument.
  23.         If N >= 0 And N <= 169 Then
  24.             ' Return the value in the array if argument is in range.
  25.             Factorial = factValues(N)
  26.         Else
  27.             ' Raise an error otherwise.
  28.             Err.Raise(6, , "Overflow")
  29.         End If
  30.     End Function
  31.  
  32.     ' --------------------------------------------------------
  33.     ' the following function is the first version of the
  34.     ' Factorial function, that doesn't take advantage of the
  35.     ' Sub New procedure for initializing the factValues array
  36.     ' --------------------------------------------------------
  37.  
  38.     ' Return the Factorial of a number in the range 0-169.
  39.     Public Function Factorial_Old(ByVal n As Integer) As Double
  40.         ' Evaluate all possible values in advance during the first call.
  41.         If factValues(0) = 0 Then
  42.             Dim i As Integer
  43.  
  44.             factValues(0) = 1
  45.             For i = 1 To 169
  46.                 factValues(i) = factValues(i - 1) * CDbl(i)
  47.             Next
  48.         End If
  49.  
  50.         ' Check the argument.
  51.         If n >= 0 And n <= 169 Then
  52.             ' Return the value in the array if argument is in range.
  53.             Factorial_Old = factValues(n)
  54.         Else
  55.             ' Raise an error otherwise.
  56.             Err.Raise(6, , "Overflow")
  57.         End If
  58.     End Function
  59. End Module
  60.